package com.base.common.util;

import java.text.ParseException;
import java.util.Date;

public class RelativeDateFormat {
	/**
	 * Defines time period
	 */
	private static final long ONE_MINUTE = 60000L;
	private static final long ONE_HOUR   = 3600000L;
	private static final long ONE_DAY	 = 86400000L;
	private static final long ONE_MONTH  = 2592000000L;
	private static final long ONE_YEAR   = 31536000000L;
	
	private static final String SECOND_AGO = "秒前";
	private static final String MINUTE_AGO = "分钟前";
	private static final String HOUR_AGO   = "小时前";
	private static final String DAY_AGO	   = "天前";
	private static final String MONTH_AGO  = "月前";
	private static final String YEAR_AGO   = "年前";
	
	public static String format(String date) throws ParseException {
		return format(Utils.StringToDate(date, "yyyy-MM-dd HH:mm:ss"));
	}
	
	public static String format(Date date) {
		long delta = new Date().getTime() - date.getTime();
		
		/*
		 * Seconds ago
		 */
		if (delta < 1L * ONE_MINUTE) {
			long seconds = toSeconds(delta);
			return (seconds <= 0 ? 1 : seconds) + SECOND_AGO;
		}
		
		/*
		 * Minutes ago
		 */
		if (delta < 1L * ONE_HOUR) {
			long minutes = toMinutes(delta);
			return (minutes <= 0 ? 1 : minutes) + MINUTE_AGO; 
		}
		
		/*
		 * Hours ago
		 */
		if (delta < 1L * ONE_DAY) {
			long hours = toHours(delta);
			return (hours <= 0 ? 1 : hours) + HOUR_AGO;
		}
		
		/*
		 * Last day
		 */
		if (delta < 48L * ONE_HOUR) {
			return "昨天(" + Utils.dateToString(date, "HH:mm") + ")";			
		}
		
		/*
		 * Days ago
		 */
		if (delta < 1L * ONE_MONTH) {
			long days = toDays(delta);
			return (days <=0 ? 1 : days) + DAY_AGO;
		}
		
		/*
		 * Months ago & Years ago
		 */
		if (delta < 1L * ONE_YEAR) {
			long months = toMonths(delta);
			return (months <= 0 ? 1 : months) + MONTH_AGO;
		} else {
			long years = toYears(delta);
			return (years <= 0 ? 1 : years) + YEAR_AGO;
		}
	}
	
	/**
	 * Converted into seconds
	 * 
	 * @param date
	 * @return seconds
	 */
	private static long toSeconds(long date) {
		return date / 1000L;
	}
	
	/**
	 * Converted into minutes
	 * 
	 * @param date
	 * @return minutes
	 */
	private static long toMinutes(long date) {
		return date / ONE_MINUTE;
	}
	
	/**
	 * Converted into hours
	 * 
	 * @param date
	 * @return hours
	 */
	private static long toHours(long date) {
		return date / ONE_HOUR;
	}
	
	/**
	 * Converted into days
	 * 
	 * @param date
	 * @return days
	 */
	private static long toDays(long date) {
		return date / ONE_DAY;
	}
	
	/**
	 * Converted into months
	 * 
	 * @param date
	 * @return months
	 */
	private static long toMonths(long date) {
		return date / ONE_MONTH;
	}
	
	/**
	 * Converted into years
	 * 
	 * @param date
	 * @return years
	 */
	private static long toYears(long date) {
		return date / ONE_YEAR;
	}
}
